package com.tsfyun.common.base.validator;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.EnumUtil;
import com.tsfyun.common.base.annotation.EnumCheck;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by Rick on 2020/3/7.
 *
 * @ Description：
 */
@Slf4j
public class EnumCheckValidator implements ConstraintValidator<EnumCheck, Object> {

    private Class clazz;

    @Override
    public void initialize(EnumCheck enumCheck) {
        clazz = enumCheck.clazz();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        if(!EnumUtil.isEnum(clazz)) {
            log.error("EnumCheck配置错误");
            return false;
        }
        //如果值为空则不校验
        if(StringUtils.isEmpty(value)) {
            return true;
        }
        //枚举类统一用code
        Map<String, Object> enumMap = EnumUtil.getNameFieldMap(clazz, "code");
        if(CollectionUtil.isNotEmpty(enumMap)) {
            List<Object> valueList = new ArrayList<>(enumMap.values());
            return valueList.contains(value);
        }
        return false;
    }
}
